import os
import json

class FileHandler:
    def __init__(self):
        # 定义存储文件的目录
        self.exams_dir = "data/exams"
        self.submissions_dir = "data/submissions"
        self.results_dir = "data/results"
        
        # 确保目录存在
        for dir_path in [self.exams_dir, self.submissions_dir, self.results_dir]:
            os.makedirs(dir_path, exist_ok=True)
    
    def save_exam(self, exam_id, exam_data):
        """保存试卷"""
        path = os.path.join(self.exams_dir, f"{exam_id}.json")
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(exam_data, f, ensure_ascii=False, indent=2)
    
    def load_exam(self, exam_id):
        """加载试卷"""
        path = os.path.join(self.exams_dir, f"{exam_id}.json")
        if not os.path.exists(path):
            return None
        with open(path, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def save_submission(self, submission_id, submission_data):
        """保存学生提交的答案"""
        path = os.path.join(self.submissions_dir, f"{submission_id}.json")
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(submission_data, f, ensure_ascii=False, indent=2)
    
    def load_submission(self, submission_id):
        """加载学生提交的答案"""
        path = os.path.join(self.submissions_dir, f"{submission_id}.json")
        if not os.path.exists(path):
            return None
        with open(path, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def save_results(self, submission_id, results_data):
        """保存批改结果"""
        path = os.path.join(self.results_dir, f"{submission_id}.json")
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(results_data, f, ensure_ascii=False, indent=2)
    
    def load_results(self, submission_id):
        """加载批改结果"""
        path = os.path.join(self.results_dir, f"{submission_id}.json")
        if not os.path.exists(path):
            return None
        with open(path, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def list_exams(self):
        """列出所有试卷"""
        return [f[:-5] for f in os.listdir(self.exams_dir) if f.endswith('.json')]
    
    def list_submissions(self):
        """列出所有提交的答卷"""
        return [f[:-5] for f in os.listdir(self.submissions_dir) if f.endswith('.json')]
    
    def list_results(self):
        """列出所有批改结果"""
        return [f[:-5] for f in os.listdir(self.results_dir) if f.endswith('.json')]